/**
 * Cookie提取器模块
 * 整合文件和内存扫描功能
 */

const path = require('path');
const fs = require('fs');
const { findCookieFiles, readCookieFile } = require('./file-scanner');
const { injectFridaScript } = require('./memory-scanner');
const { promisify } = require('util');
const { Buffer } = require('buffer');
const plist = require('plist');
const xml2js = require('xml2js');
const readFileAsync = promisify(fs.readFile);
const sqlite3 = require('sqlite3').verbose();

/**
 * 从进程提取Cookie
 * @param {Object} proc - 进程信息对象
 * @param {Object} options - 提取选项
 * @returns {Promise<Array>} - 提取到的Cookie数组
 */
async function extractCookiesFromProcess(proc, options = {}) {
  const { method = 'all', outputDir = 'cookies_extracted' } = options;
  const cookies = [];
  
  // 确保输出目录存在
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
  
  // 根据选择的方法提取Cookie
  if (method === 'files' || method === 'all') {
    // 从文件中提取
    const cookieFiles = await findCookieFiles(proc);
    
    for (const file of cookieFiles) {
      try {
        console.log(`正在读取文件: ${file}`);
        const fileCookies = await readCookieFile(file);
        
        if (fileCookies.length > 0) {
          console.log(`从文件中提取了 ${fileCookies.length} 个Cookie`);
          cookies.push(...fileCookies);
        }
      } catch (err) {
        console.error(`无法读取Cookie文件 ${file}: ${err.message}`);
      }
    }
  }
  
  if (method === 'memory' || method === 'all') {
    // 从内存中提取
    try {
      console.log('正在从内存中提取Cookie...');
      const memoryCookies = await injectFridaScript(proc.pid);
      
      if (memoryCookies.length > 0) {
        console.log(`从内存中提取了 ${memoryCookies.length} 个Cookie`);
        cookies.push(...memoryCookies);
      }
    } catch (err) {
      console.error(`从内存提取Cookie时出错: ${err.message}`);
    }
  }
  
  // 去重
  return [...new Map(cookies.map(c => [c.name + c.value, c])).values()];
}

/**
 * 保存提取的Cookie到文件
 * @param {Array} cookies - Cookie数组
 * @param {Object} proc - 进程信息
 * @param {string} outputDir - 输出目录
 * @returns {Object} - 保存的文件路径
 */
function saveCookies(cookies, proc, outputDir) {
  if (cookies.length === 0) {
    return null;
  }
  
  const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');
  const outputFile = path.join(outputDir, `cookies_${proc.pid}_${timestamp}.json`);
  
  fs.writeFileSync(outputFile, JSON.stringify(cookies, null, 2));
  
  // 创建分类文件
  const categories = categorizeCookies(cookies);
  const categoryFile = path.join(outputDir, `categories_${proc.pid}_${timestamp}.json`);
  fs.writeFileSync(categoryFile, JSON.stringify(categories, null, 2));
  
  // 为每个类别创建一个单独的文件
  for (const [category, catCookies] of Object.entries(categories)) {
    if (catCookies.length > 0) {
      const catFile = path.join(outputDir, `${category}_${proc.pid}_${timestamp}.json`);
      fs.writeFileSync(catFile, JSON.stringify(catCookies, null, 2));
    }
  }
  
  return {
    mainFile: outputFile,
    categoryFile,
    categories: Object.keys(categories).filter(cat => categories[cat].length > 0)
  };
}

/**
 * 对Cookie进行分类
 * @param {Array} cookies - Cookie数组
 * @returns {Object} - 分类结果
 */
function categorizeCookies(cookies) {
  const categories = {
    authentication: [],
    session: [],
    tracking: [],
    preference: [],
    analytics: [],
    functional: [],
    other: []
  };
  
  for (const cookie of cookies) {
    const name = (cookie.name || '').toLowerCase();
    
    // 认证相关
    if (name.includes('token') || 
        name.includes('auth') || 
        name.includes('login') || 
        name.includes('access') || 
        name.includes('jwt') || 
        name.includes('refresh') || 
        name.includes('id_')) {
      categories.authentication.push(cookie);
    }
    // 会话相关
    else if (name.includes('session') || 
             name.includes('sid') || 
             name.includes('sess')) {
      categories.session.push(cookie);
    }
    // 跟踪相关
    else if (name.includes('track') || 
             name.includes('visitor') || 
             name.includes('uid') || 
             name.includes('uuid') || 
             name.includes('guid')) {
      categories.tracking.push(cookie);
    }
    // 偏好相关
    else if (name.includes('pref') || 
             name.includes('setting') || 
             name.includes('config') || 
             name.includes('theme')) {
      categories.preference.push(cookie);
    }
    // 分析相关
    else if (name.includes('ga') || 
             name.includes('analytics') || 
             name.includes('metric') || 
             name.includes('stat')) {
      categories.analytics.push(cookie);
    }
    // 功能性
    else if (name.includes('feature') || 
             name.includes('func') || 
             name.includes('api') || 
             name.includes('app')) {
      categories.functional.push(cookie);
    }
    // 其他
    else {
      categories.other.push(cookie);
    }
  }
  
  return categories;
}

/**
 * 从Cookie文件中提取数据
 * @param {string} filePath - Cookie文件路径 
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractCookies(filePath) {
  if (!filePath || !fs.existsSync(filePath)) {
    return [];
  }
  
  try {
    const extension = path.extname(filePath).toLowerCase();
    const fileName = path.basename(filePath).toLowerCase();
    
    // 根据文件类型选择相应的提取方法
    if (fileName === 'cookies' || fileName === 'cookies-journal') {
      // Chrome/Electron SQLite格式
      return await extractSqliteCookies(filePath);
    } else if (extension === '.sqlite' || extension === '.db') {
      // SQLite数据库格式
      return await extractSqliteCookies(filePath);
    } else if (extension === '.json' || fileName === 'preferences') {
      // JSON格式
      return await extractJsonCookies(filePath);
    } else if (extension === '.xml' || extension === '.config') {
      // XML格式（常见于.NET应用）
      return await extractXmlCookies(filePath);
    } else if (extension === '.plist') {
      // macOS plist格式
      return await extractPlistCookies(filePath);
    } else if (fileName === 'cookies.binarycookies' || fileName.includes('binarycookies')) {
      // macOS二进制Cookie格式
      return await extractBinaryCookies(filePath);
    } else if (extension === '.dat' || extension === '.bin') {
      // 二进制数据文件（尝试不同的提取方法）
      return await extractBinaryData(filePath);
    } else if (extension === '.ini' || extension === '.txt') {
      // 文本配置文件
      return await extractTextCookies(filePath);
    } else {
      // 尝试作为文本文件读取
      return await extractTextCookies(filePath);
    }
  } catch (err) {
    console.error(`提取Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从SQLite数据库文件中提取Cookie
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractSqliteCookies(filePath) {
  return new Promise((resolve, reject) => {
    try {
      const db = new sqlite3.Database(filePath, sqlite3.OPEN_READONLY, (err) => {
        if (err) {
          console.warn(`打开SQLite数据库失败: ${err.message}`);
          resolve([]);
          return;
        }
        
        // 尝试不同的Cookie表结构查询
        const queries = [
          // Chrome/Electron格式
          `SELECT host_key as domain, name, value, path, expires_utc as expires, 
           secure, httponly, creation_utc as creation, last_access_utc as lastAccess
           FROM cookies`,
          // Firefox格式
          `SELECT host as domain, name, value, path, expiry as expires, 
           isSecure as secure, isHttpOnly as httponly, creationTime as creation
           FROM moz_cookies`,
          // 通用表结构1
          `SELECT domain, name, value, path, expires, secure, httpOnly 
           FROM cookies`,
          // 通用表结构2
          `SELECT * FROM cookies`,
          // 查询其他可能的表
          `SELECT name FROM sqlite_master WHERE type='table'`
        ];
        
        let results = [];
        let queryIndex = 0;
        
        const tryNextQuery = () => {
          if (queryIndex >= queries.length) {
            db.close();
            resolve(results);
            return;
          }
          
          const query = queries[queryIndex++];
          
          db.all(query, [], (err, rows) => {
            if (err) {
              // 尝试下一个查询
              tryNextQuery();
              return;
            }
            
            if (rows && rows.length > 0) {
              if (query.includes('sqlite_master')) {
                // 如果是表名查询，查找可能的cookie表
                const cookieTables = rows.filter(row => 
                  row.name && row.name.toLowerCase().includes('cookie'));
                
                if (cookieTables.length > 0) {
                  // 尝试从找到的cookie表中查询数据
                  for (const table of cookieTables) {
                    db.all(`SELECT * FROM ${table.name}`, [], (err, tableRows) => {
                      if (!err && tableRows && tableRows.length > 0) {
                        results = results.concat(normalizeCookies(tableRows));
                      }
                    });
                  }
                }
              } else {
                // 标准cookie查询
                results = normalizeCookies(rows);
                db.close();
                resolve(results);
                return;
              }
            }
            
            // 尝试下一个查询
            tryNextQuery();
          });
        };
        
        tryNextQuery();
      });
    } catch (err) {
      console.error(`提取SQLite Cookie出错: ${err.message}`);
      resolve([]);
    }
  });
}

/**
 * 从JSON文件中提取Cookie
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractJsonCookies(filePath) {
  try {
    const data = await readFileAsync(filePath, 'utf8');
    const jsonData = JSON.parse(data);
    
    // 尝试不同的JSON结构
    const cookieData = [];
    
    // Chrome/Electron Preferences文件
    if (jsonData.profile && jsonData.profile.cookies) {
      return normalizeCookies(jsonData.profile.cookies);
    }
    
    // Electron localStorage文件
    if (jsonData.cookies || jsonData.cookie) {
      return normalizeCookies(jsonData.cookies || jsonData.cookie);
    }
    
    // 检查是否为标准cookie数组
    if (Array.isArray(jsonData)) {
      return normalizeCookies(jsonData);
    }
    
    // 检查所有可能的cookie字段
    const cookieFields = [
      'cookies', 'cookie', 'cookiejar', 'cookieStore', 'cookieContainer',
      'session', 'sessions', 'credential', 'credentials', 'auth', 
      'authentication', 'token', 'tokens'
    ];
    
    for (const field of cookieFields) {
      if (jsonData[field]) {
        if (typeof jsonData[field] === 'string') {
          // 可能是序列化的JSON字符串
          try {
            const parsedData = JSON.parse(jsonData[field]);
            return normalizeCookies(parsedData);
          } catch (e) {
            // 不是有效的JSON
            continue;
          }
        } else {
          return normalizeCookies(jsonData[field]);
        }
      }
    }
    
    // 如果没有找到明确的cookie字段，尝试扫描所有字段
    const cookies = scanJsonForCookies(jsonData);
    return cookies;
  } catch (err) {
    console.error(`提取JSON Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从XML文件中提取Cookie (用于.NET应用等)
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractXmlCookies(filePath) {
  try {
    const data = await readFileAsync(filePath, 'utf8');
    const parser = new xml2js.Parser({ explicitArray: false });
    const result = await promisify(parser.parseString)(data);
    
    let cookies = [];
    
    // 处理.NET用户配置文件
    if (result && result.configuration && result.configuration.userSettings) {
      const settings = result.configuration.userSettings;
      
      // 遍历所有设置组
      for (const settingGroup in settings) {
        const group = settings[settingGroup];
        
        if (group.setting) {
          const cookieSettings = Array.isArray(group.setting) ? 
            group.setting : [group.setting];
          
          for (const setting of cookieSettings) {
            // 检查是否为cookie相关设置
            if (setting.$.name && 
                (setting.$.name.toLowerCase().includes('cookie') || 
                 setting.$.name.toLowerCase().includes('token') || 
                 setting.$.name.toLowerCase().includes('auth'))) {
              
              if (setting.value) {
                // 尝试将值解析为JSON
                try {
                  const cookieData = JSON.parse(setting.value);
                  cookies = cookies.concat(normalizeCookies(cookieData));
                } catch (e) {
                  // 不是JSON，可能是单个cookie值
                  cookies.push({
                    name: setting.$.name,
                    value: setting.value,
                    domain: '',
                    path: '/'
                  });
                }
              }
            }
          }
        }
      }
    }
    
    // 处理其他XML格式
    if (result && result.cookies && result.cookies.cookie) {
      const xmlCookies = Array.isArray(result.cookies.cookie) ? 
        result.cookies.cookie : [result.cookies.cookie];
      
      for (const cookie of xmlCookies) {
        cookies.push({
          name: cookie.name || cookie.$.name,
          value: cookie.value || cookie.$.value,
          domain: cookie.domain || cookie.$.domain || '',
          path: cookie.path || cookie.$.path || '/'
        });
      }
    }
    
    return cookies;
  } catch (err) {
    console.error(`提取XML Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从macOS plist文件中提取Cookie
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractPlistCookies(filePath) {
  try {
    const data = await readFileAsync(filePath, 'utf8');
    const plistData = plist.parse(data);
    
    let cookies = [];
    
    // 处理不同格式的plist
    if (plistData.Cookies) {
      // 标准cookie数组
      cookies = normalizeCookies(plistData.Cookies);
    } else if (plistData.NSHTTPCookieStorage) {
      // macOS NSHTTPCookieStorage格式
      const cookieStorage = plistData.NSHTTPCookieStorage;
      
      if (cookieStorage.Cookies) {
        cookies = normalizeCookies(cookieStorage.Cookies);
      }
    } else {
      // 扫描plist中所有可能的cookie
      cookies = scanPlistForCookies(plistData);
    }
    
    return cookies;
  } catch (err) {
    console.error(`提取plist Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从macOS二进制Cookie文件中提取数据
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractBinaryCookies(filePath) {
  try {
    const buffer = await readFileAsync(filePath);
    
    // 二进制Cookie格式分析 - 简化实现，仅提取可能的字符串
    const strings = extractStringsFromBinary(buffer);
    
    const cookies = [];
    let currentCookie = {};
    let lastKey = '';
    
    // 尝试识别cookie键值对
    for (const str of strings) {
      if (str.startsWith('.') || str.includes('.') && !str.includes(' ')) {
        // 可能是域名
        if (Object.keys(currentCookie).length > 0) {
          cookies.push(currentCookie);
          currentCookie = {};
        }
        
        currentCookie.domain = str;
        lastKey = 'domain';
      } else if (str === '/' || str.startsWith('/')) {
        // 可能是路径
        currentCookie.path = str;
        lastKey = 'path';
      } else if (['TRUE', 'FALSE', 'true', 'false'].includes(str)) {
        // 可能是布尔值属性
        if (lastKey === 'secure') {
          currentCookie.secure = str.toLowerCase() === 'true';
        } else if (lastKey === 'httponly') {
          currentCookie.httpOnly = str.toLowerCase() === 'true';
        } else {
          // 假设是secure标志
          currentCookie.secure = str.toLowerCase() === 'true';
          lastKey = 'secure';
        }
      } else if (str.length > 0) {
        // 可能是cookie名称或值
        if (!currentCookie.name) {
          currentCookie.name = str;
          lastKey = 'name';
        } else if (!currentCookie.value) {
          currentCookie.value = str;
          lastKey = 'value';
        }
      }
    }
    
    // 添加最后一个cookie
    if (Object.keys(currentCookie).length > 0) {
      cookies.push(currentCookie);
    }
    
    return cookies;
  } catch (err) {
    console.error(`提取二进制Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从二进制数据文件中提取可能的Cookie数据
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractBinaryData(filePath) {
  try {
    const buffer = await readFileAsync(filePath);
    
    // 先尝试作为SQLite打开
    try {
      return await extractSqliteCookies(filePath);
    } catch (e) {
      // 不是SQLite文件，继续尝试其他方法
    }
    
    // 尝试提取字符串
    const strings = extractStringsFromBinary(buffer);
    
    // 尝试识别JSON结构
    for (const str of strings) {
      if (str.startsWith('{') && str.endsWith('}')) {
        try {
          const jsonData = JSON.parse(str);
          const cookies = scanJsonForCookies(jsonData);
          if (cookies.length > 0) {
            return cookies;
          }
        } catch (e) {
          // 不是JSON，继续
        }
      }
    }
    
    // 尝试识别cookie键值对
    return extractCookiePairsFromStrings(strings);
  } catch (err) {
    console.error(`提取二进制数据出错: ${err.message}`);
    return [];
  }
}

/**
 * 从文本文件中提取Cookie数据
 * @param {string} filePath - 文件路径
 * @returns {Promise<Array>} - 提取的Cookie数据
 */
async function extractTextCookies(filePath) {
  try {
    const data = await readFileAsync(filePath, 'utf8');
    const lines = data.split(/\r?\n/);
    
    // 尝试不同的文本格式
    
    // 1. 检查是否为JSON格式
    if (data.trim().startsWith('{') || data.trim().startsWith('[')) {
      try {
        const jsonData = JSON.parse(data);
        return extractJsonCookies(filePath);
      } catch (e) {
        // 不是有效的JSON
      }
    }
    
    // 2. 检查是否为XML格式
    if (data.trim().startsWith('<?xml') || data.trim().startsWith('<')) {
      try {
        return await extractXmlCookies(filePath);
      } catch (e) {
        // 不是有效的XML
      }
    }
    
    // 3. 检查是否为Netscape cookie格式
    if (lines[0] && lines[0].includes('# Netscape HTTP Cookie File')) {
      return parseNetscapeCookieFile(lines);
    }
    
    // 4. 检查是否为键值对格式
    const cookies = [];
    let currentCookie = {};
    
    for (const line of lines) {
      const trimmedLine = line.trim();
      
      // 跳过空行和注释
      if (!trimmedLine || trimmedLine.startsWith('#') || trimmedLine.startsWith('//')) {
        continue;
      }
      
      // 检查是否为INI格式的节
      if (trimmedLine.startsWith('[') && trimmedLine.endsWith(']')) {
        if (Object.keys(currentCookie).length > 0) {
          cookies.push(currentCookie);
        }
        currentCookie = { name: trimmedLine.slice(1, -1) };
        continue;
      }
      
      // 尝试解析键值对
      const match = trimmedLine.match(/^([^=:]+)[=:](.*)$/);
      if (match) {
        const key = match[1].trim();
        const value = match[2].trim();
        
        // 检查是否为cookie字段
        if (['domain', 'path', 'expires', 'secure', 'httponly'].includes(key.toLowerCase())) {
          currentCookie[key.toLowerCase()] = value;
        } else if (key.toLowerCase() === 'name') {
          currentCookie.name = value;
        } else if (key.toLowerCase() === 'value') {
          currentCookie.value = value;
        } else if (!currentCookie.name) {
          // 如果没有明确的name字段，使用第一个键作为名称
          currentCookie.name = key;
          currentCookie.value = value;
        }
      }
    }
    
    // 添加最后一个cookie
    if (Object.keys(currentCookie).length > 0) {
      cookies.push(currentCookie);
    }
    
    return cookies;
  } catch (err) {
    console.error(`提取文本Cookie出错: ${err.message}`);
    return [];
  }
}

/**
 * 从二进制数据中提取字符串
 * @param {Buffer} buffer - 二进制数据
 * @returns {Array<string>} - 提取的字符串数组
 */
function extractStringsFromBinary(buffer) {
  const strings = [];
  let currentString = '';
  
  for (let i = 0; i < buffer.length; i++) {
    const byte = buffer[i];
    
    // 检查是否为可打印ASCII字符
    if (byte >= 32 && byte <= 126) {
      currentString += String.fromCharCode(byte);
    } else if (currentString.length >= 3) {
      // 字符串长度至少为3
      strings.push(currentString);
      currentString = '';
    } else {
      currentString = '';
    }
  }
  
  // 添加最后一个字符串
  if (currentString.length >= 3) {
    strings.push(currentString);
  }
  
  return strings;
}

/**
 * 从字符串数组中提取cookie键值对
 * @param {Array<string>} strings - 字符串数组
 * @returns {Array} - 提取的Cookie数据
 */
function extractCookiePairsFromStrings(strings) {
  const cookies = [];
  let currentCookie = {};
  
  for (let i = 0; i < strings.length; i++) {
    const str = strings[i];
    
    // 检查是否为cookie键
    if (str.toLowerCase() === 'name' && i + 1 < strings.length) {
      if (Object.keys(currentCookie).length > 0) {
        cookies.push(currentCookie);
        currentCookie = {};
      }
      currentCookie.name = strings[i + 1];
      i++;
    } else if (str.toLowerCase() === 'value' && i + 1 < strings.length) {
      currentCookie.value = strings[i + 1];
      i++;
    } else if (str.toLowerCase() === 'domain' && i + 1 < strings.length) {
      currentCookie.domain = strings[i + 1];
      i++;
    } else if (str.toLowerCase() === 'path' && i + 1 < strings.length) {
      currentCookie.path = strings[i + 1];
      i++;
    } else if (str.toLowerCase() === 'expires' && i + 1 < strings.length) {
      currentCookie.expires = strings[i + 1];
      i++;
    } else if (str.includes('=')) {
      // 可能是"name=value"格式
      const parts = str.split('=');
      if (parts.length === 2) {
        const key = parts[0].trim();
        const value = parts[1].trim();
        
        if (!currentCookie.name) {
          currentCookie.name = key;
          currentCookie.value = value;
        }
      }
    }
  }
  
  // 添加最后一个cookie
  if (Object.keys(currentCookie).length > 0) {
    cookies.push(currentCookie);
  }
  
  return cookies;
}

/**
 * 扫描JSON对象查找可能的cookie数据
 * @param {Object} jsonData - JSON对象
 * @returns {Array} - 找到的cookie数组
 */
function scanJsonForCookies(jsonData) {
  const cookies = [];
  
  // 如果是数组，检查每个元素
  if (Array.isArray(jsonData)) {
    for (const item of jsonData) {
      if (typeof item === 'object' && item !== null) {
        // 检查是否为cookie对象
        if (item.name && (item.value !== undefined || item.content !== undefined)) {
          cookies.push({
            name: item.name,
            value: item.value || item.content || '',
            domain: item.domain || item.host || '',
            path: item.path || '/',
            expires: item.expires || item.expiry || '',
            secure: !!item.secure,
            httpOnly: !!item.httpOnly
          });
        } else {
          // 递归检查子对象
          const childCookies = scanJsonForCookies(item);
          cookies.push(...childCookies);
        }
      }
    }
  } else if (typeof jsonData === 'object' && jsonData !== null) {
    // 检查对象的所有键
    for (const key in jsonData) {
      const value = jsonData[key];
      
      // 检查值是否为对象或数组
      if (typeof value === 'object' && value !== null) {
        // 递归检查子对象
        const childCookies = scanJsonForCookies(value);
        cookies.push(...childCookies);
      } else if (typeof key === 'string' && typeof value === 'string') {
        // 检查是否为cookie键值对
        if (key.includes('cookie') || key.includes('token')) {
          try {
            // 尝试解析为JSON
            const parsedValue = JSON.parse(value);
            const childCookies = scanJsonForCookies(parsedValue);
            cookies.push(...childCookies);
          } catch (e) {
            // 不是JSON，可能是单个cookie值
            cookies.push({
              name: key,
              value: value,
              domain: '',
              path: '/'
            });
          }
        }
      }
    }
  }
  
  return cookies;
}

/**
 * 扫描plist对象查找可能的cookie数据
 * @param {Object} plistData - plist对象
 * @returns {Array} - 找到的cookie数组
 */
function scanPlistForCookies(plistData) {
  // 与scanJsonForCookies类似的实现
  return scanJsonForCookies(plistData);
}

/**
 * 解析Netscape格式的cookie文件
 * @param {Array<string>} lines - 文件行
 * @returns {Array} - 提取的Cookie数据
 */
function parseNetscapeCookieFile(lines) {
  const cookies = [];
  
  for (const line of lines) {
    if (line.startsWith('#') || !line.trim()) {
      continue;
    }
    
    const parts = line.split(/\t/);
    if (parts.length < 6) {
      continue;
    }
    
    cookies.push({
      domain: parts[0],
      path: parts[2],
      secure: parts[3] === 'TRUE',
      expires: parts[4],
      name: parts[5],
      value: parts[6] || ''
    });
  }
  
  return cookies;
}

/**
 * 标准化cookie对象
 * @param {Array|Object} cookieData - 待标准化的cookie数据
 * @returns {Array} - 标准化后的cookie数组
 */
function normalizeCookies(cookieData) {
  if (!cookieData) return [];
  
  // 确保处理的是数组
  const cookieArray = Array.isArray(cookieData) ? cookieData : [cookieData];
  const result = [];
  
  for (let cookie of cookieArray) {
    // 跳过非对象
    if (typeof cookie !== 'object' || cookie === null) {
      continue;
    }
    
    // 标准化属性名
    const normalizedCookie = {
      name: cookie.name || cookie.Name || cookie.key || cookie.Key || '',
      value: cookie.value || cookie.Value || cookie.content || cookie.Content || '',
      domain: cookie.domain || cookie.Domain || cookie.host || cookie.Host || cookie.host_key || cookie.HostKey || '',
      path: cookie.path || cookie.Path || '/',
      expires: cookie.expires || cookie.Expires || cookie.expiry || cookie.Expiry || '',
      secure: !!cookie.secure || !!cookie.Secure,
      httpOnly: !!cookie.httpOnly || !!cookie.HttpOnly || !!cookie.httponly
    };
    
    // 确保必要的字段存在
    if (normalizedCookie.name) {
      result.push(normalizedCookie);
    }
  }
  
  return result;
}

module.exports = {
  extractCookiesFromProcess,
  saveCookies,
  categorizeCookies,
  extractCookies,
  extractSqliteCookies,
  extractJsonCookies,
  extractXmlCookies,
  extractPlistCookies,
  extractBinaryCookies,
  extractTextCookies
}; 